package sharedprefs

import (
	"encoding/xml"
	"fmt"
	"strconv"
)

func Parse(b []byte) (*Prefs, error) {
	p := &prefs{}
	if err := xml.Unmarshal(b, &p); err != nil {
		return nil, err
	}
	return &Prefs{prefs: p}, nil
}

type Prefs struct {
	prefs *prefs
}

type prefs struct {
	Key     xml.Name `xml:"map"`
	Strings []*elem  `xml:"string"`
	Bools   []*elem  `xml:"boolean"`
	Ints    []*elem  `xml:"int"`
	Longs   []*elem  `xml:"long"`
	Sets    []*elem  `xml:"set"`
}

type elem struct {
	Name  string `xml:"name,attr"`
	Value string `xml:"value,attr"`
	Text  string `xml:",chardata"`
}

var ErrNotFound = fmt.Errorf("not found")

func (p *Prefs) String(name string) (string, error) {
	for _, e := range p.prefs.Strings {
		if e.Name == name {
			return e.Text, nil
		}
	}
	return "", ErrNotFound
}

func (p *Prefs) Int(name string) (int, error) {
	for _, e := range p.prefs.Ints {
		if e.Name == name {
			return strconv.Atoi(e.Value)
		}
	}
	return 0, ErrNotFound
}

func (p *Prefs) Long(name string) (int64, error) {
	for _, e := range p.prefs.Longs {
		if e.Name == name {
			return strconv.ParseInt(e.Value, 10, 64)
		}
	}
	return 0, ErrNotFound
}

func (p *Prefs) Boolean(name string) (bool, error) {
	for _, e := range p.prefs.Bools {
		if e.Name == name {
			return strconv.ParseBool(e.Value)
		}
	}
	return false, ErrNotFound
}
